package com.example.capsule.config;

import com.example.capsule.filter.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authz -> authz
                        // 允许静态资源访问
                        .requestMatchers("/").permitAll()
                        .requestMatchers("/index.html").permitAll()
                        .requestMatchers("/static/**").permitAll()
                        .requestMatchers("/*.html").permitAll()
                        .requestMatchers("/*.css").permitAll()
                        .requestMatchers("/*.js").permitAll()
                        .requestMatchers("/*.ico").permitAll()
                        .requestMatchers("/favicon.ico").permitAll()

                        // API 访问权限
                        .requestMatchers("/api/capsules/public").permitAll()
                        .requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/api/files/**").permitAll()
                        .requestMatchers("/upload/**").permitAll()

                        // Swagger 文档
                        .requestMatchers("/swagger-ui/**").permitAll()
                        .requestMatchers("/api-docs/**").permitAll()
                        .requestMatchers("/v3/api-docs/**").permitAll()

                        // 邀请相关页面和API
                        .requestMatchers("/invitation/**").permitAll()

                        // 公开的接受邀请接口
                        .requestMatchers("/api/invitations/accept-public").permitAll()
                        .requestMatchers("/api/invitations/accept-by-token").permitAll()
                        .requestMatchers("/api/invitations/accept-by-link").permitAll()
                        .requestMatchers("/api/invitations/invitation-info").permitAll()
                        .requestMatchers("/api/invitations/token-info").permitAll()

                        // 需要认证的邀请API
                        .requestMatchers("/api/invitations/accept").authenticated()
                        .requestMatchers("/api/invitations/create").authenticated()
                        .requestMatchers("/api/invitations/my-invitations").authenticated()
                        .requestMatchers("/api/invitations/pending-count").authenticated()
                        .requestMatchers("/api/invitations/capsule/**").authenticated()
                        .requestMatchers("/api/invitations/**").authenticated()

                        // 需要认证的胶囊API
                        .requestMatchers("/api/capsules/my-created").authenticated()
                        .requestMatchers("/api/capsules/my-received").authenticated()
                        .requestMatchers("/api/capsules/**").authenticated()

                        // 其他所有请求允许访问（主要是静态资源）
                        .anyRequest().permitAll()
                )
                // 添加JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}